import React, { Component } from "react";
import "../assets/css/AddAddress.css";
import PageHeader from "../components/PageHeader";
import Phone from "../components/Phone";
import { Switch, PickerView } from "antd-mobile";
import login from "../hooks/loginInfo";
import Popup from "../components/Popup";
import checkPhone from "../hooks/checkPhone";
import { errorToast, successToast } from "../components/Toast";
import Loading from "../components/Loading";

class AddAddress extends Component {
  constructor(props) {
    super(props);

    this.state = {
      name: "",
      phone: "",
      address: "",
      detailAddress: "",
      postalCode: "",
      checked: false,
      token: null,
      province: null,
      value: [1, 2, 3],
      showPicker: false,
    };
    this.changeName = this.changeName.bind(this);
    this.changePhone = this.changePhone.bind(this);
    this.changeDetailAddress = this.changeDetailAddress.bind(this);
    this.changePostalCode = this.changePostalCode.bind(this);
    this.selectedAddrss = this.selectedAddrss.bind(this);
    this.Picker = this.Picker.bind(this);
    this.affirmAddress = this.affirmAddress.bind(this);
    this.save = this.save.bind(this);
  }

  save() {
    if (
      this.state.name !== "" &&
      this.state.phone !== "" &&
      this.state.address !== "" &&
      this.state.detailAddress !== "" &&
      this.state.postalCode !== ""
    ) {
      if (checkPhone(this.state.phone)) {
        this.$axios
          .post("/addAddress", {
            tokenString: this.state.token,
            name: this.state.name,
            tel: this.state.phone,
            province: this.state.address[0],
            city: this.state.address[1],
            county: this.state.address[2],
            addressDetail: this.state.detailAddress,
            areaCode: "",
            postalCode: this.state.postalCode,
            isDefault: this.state.checked ? 1 : 0,
          })
          .then((res) => {
            successToast(res.data.msg);
            this.props.history.goBack();
          });
      } else {
        errorToast("手机号码格式不正确");
      }
    } else {
      errorToast("请填写完整信息");
    }
  }
  affirmAddress() {
    var index1 = this.state.province.findIndex((item) => {
      return item.value === this.state.value[0];
    });
    var index2 = this.state.province[index1].children.findIndex((item) => {
      return item.value === this.state.value[1];
    });
    var index3 = this.state.province[index1].children[
      index2
    ].children.findIndex((item) => {
      return item.value === this.state.value[2];
    });
    this.setState({
      address: [
        this.state.province[index1].label,
        this.state.province[index1].children[index2].label,
        this.state.province[index1].children[index2].children[index3].label,
      ],
    });
    this.selectedAddrss();
  }
  Picker(value) {
    this.setState({
      value,
    });
  }
  selectedAddrss() {
    this.setState({
      showPicker: !this.state.showPicker,
    });
  }
  changeName(e) {
    this.setState({
      name: e.target.value,
    });
  }
  changePhone(e) {
    this.setState({
      phone: e.target.value,
    });
  }
  changeDetailAddress(e) {
    this.setState({
      detailAddress: e.target.value,
    });
  }
  changePostalCode(e) {
    this.setState({
      postalCode: e.target.value,
    });
  }

  componentWillMount() {
    var loginInfo = login();
    this.setState({
      token: loginInfo.token,
    });
    this.$axios.get("http://47.115.51.185/api/city_list").then((res) => {
      function a(data) {
        var obj = [];
        data.forEach((item) => {
          var o = {};
          for (const key in item) {
            if (Array.isArray(item[key]) !== true) {
              if (key === "n") {
                o["label"] = item[key];
              } else if (key === "v") {
                o["value"] = item[key];
              }
            } else {
              o["children"] = a(item[key]);
            }
          }
          obj.push(o);
        });
        return obj;
      }
      var datas = a(res.data.data);
      this.setState({
        province: datas,
      });
    });
  }

  render() {
    return (
      <div className="AddAddress">
        <PageHeader>
          <span slot="title">新增地址</span>
        </PageHeader>
        {this.state.province ? (
          <div className="AddAddress_content">
            <div className="AddAddress_content_form">
              <Phone
                title="姓名"
                placeholder="收货人姓名"
                ChangePhone={this.changeName}
              ></Phone>
              <Phone
                title="电话"
                placeholder="收货人手机号码"
                ChangePhone={this.changePhone}
              ></Phone>
              <div className="phone" onClick={this.selectedAddrss}>
                <span className="text">地区</span>
                <input
                  className="Input"
                  readOnly={true}
                  type="text"
                  defaultValue={this.state.address}
                  placeholder={
                    this.state.address
                      ? this.state.address.join("/").slice(0, -1)
                      : "选择省/市/区"
                  }
                />
                <i
                  className="password_show_icon"
                  style={{
                    backgroundImage: ` url(${
                      require(`../assets/images/arrowRight.png`).default
                    })`,
                  }}
                ></i>
              </div>
              <Phone
                title="详细地址"
                placeholder="街道门牌、楼层房间号等信息"
                ChangePhone={this.changeDetailAddress}
              ></Phone>
              <Phone
                title="邮政编码"
                placeholder="邮政编码"
                ChangePhone={this.changePostalCode}
              ></Phone>
            </div>
            <div className="AddAddress_content_default">
              <span>设为默认收货地址</span>
              <div>
                <Switch
                  color="#0c34ba"
                  checked={this.state.checked}
                  onChange={() => {
                    this.setState({
                      checked: !this.state.checked,
                    });
                  }}
                />
              </div>
            </div>
            <button className="save" onClick={this.save}>
              保存
            </button>
            {this.state.showPicker && this.state.province && (
              <Popup closePopup={this.selectedAddrss}>
                <div className="pickAddress">
                  <span onClick={this.affirmAddress}>确认</span>
                </div>
                <PickerView
                  onChange={this.Picker}
                  data={this.state.province}
                  value={this.state.value}
                />
              </Popup>
            )}
          </div>
        ) : (
          <Loading></Loading>
        )}
      </div>
    );
  }
}

export default AddAddress;
